package com.cucn.ingmall.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.TypeReference;
import com.cucn.common.constant.auth.SmsConstant;
import com.cucn.common.exception.BizCodeEnume;
import com.cucn.common.to.dto.MemberResponseDTO;
import com.cucn.common.utils.R;
import com.cucn.common.utils.RandomUtils;
import com.cucn.ingmall.auth.feign.MemberFeignService;
import com.cucn.ingmall.auth.feign.ThirdPartyFeignService;
import com.cucn.ingmall.auth.vo.MemberRegistVO;
import com.cucn.ingmall.auth.vo.UserLoginVO;
import com.cucn.ingmall.auth.vo.UserRegistVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 登录页controller
 *
 * @author KouChaoJie
 * @since: 2022/1/7 09:32
 */
@Controller
@Slf4j
public class LoginController {

    @Resource
    private ThirdPartyFeignService thirdPartyFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MemberFeignService memberFeignService;

    /**
     * 验证码发送
     *
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R send(@RequestParam("phone") String phone) {
        //KouTODO:2022/1/7 16:10 Kou 接口防刷
        String redisCode = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //注意腾讯云验证码只能接收0-6位纯数字!!!!
        //给验证码加上时间,以便在存入redis时方便验证是否是60s内已发送的验证码,如果是,则不发送
        String code = RandomUtils.getSixBitRandom() + "_" + System.currentTimeMillis();

        //发送成功,把发送成功的验证码放到redis缓存里,并设置有效时间
        log.info("调用短信服务发送验证码,手机号={},验证码={}", phone, code.substring(0, 6));
        R r = thirdPartyFeignService.sendCode(phone, code.substring(0, 6));
        stringRedisTemplate.opsForValue().set(SmsConstant.SMS_CODE_CACHE_PREFIX + phone, code, 5, TimeUnit.MINUTES);

        return R.ok();
    }

    //KouTODO:2022/1/9 16:03 Kou 分布式下session会出现的问题

    /**
     * 注册完成重定向到登录页
     * 重定向携带数据，利用session原理。将数据放在session中。
     * 只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉
     *
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVO userRegistVO, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            //将错误信息传递给前端
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));

            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错,转发到注册页
            return "redirect:http://auth.koukoucoding.xn--fiqs8s/reg.html";
        }

        //真正注册,调用远程服务进行注册
        //校验验证码
        String code = userRegistVO.getCode();
        String codeRedisKey = stringRedisTemplate.opsForValue().get(SmsConstant.SMS_CODE_CACHE_PREFIX + userRegistVO.getPhone());
        if (!StringUtils.isEmpty(code)) {
            if (code.equals(codeRedisKey.split("_")[0])) {

                //验证码校验通过,调用远程服务进行注册
                MemberRegistVO vo = new MemberRegistVO();
                BeanUtils.copyProperties(userRegistVO, vo);
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //成功
                    return "redirect:http://auth.koukoucoding.xn--fiqs8s/login.html";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    //放入错误消息
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.koukoucoding.xn--fiqs8s/reg.html";
                }

            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");

                redirectAttributes.addFlashAttribute("errors", errors);
                //校验出错,转发到注册页
                return "redirect:http://auth.koukoucoding.xn--fiqs8s/reg.html";
            }

        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");

            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错,转发到注册页
            return "redirect:http://auth.koukoucoding.xn--fiqs8s/reg.html";
        }

        //校验成功,重定向到登录页
    }

    /**
     * 用户登录请求
     *
     * @param loginVO 登录vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVO loginVO, RedirectAttributes redirectAttributes, HttpSession session) {
        log.info("{}用户发起登录请求,进行远程服务调用...", loginVO.getLoginacct());
        R r = memberFeignService.login(loginVO);
        if (r.getCode() == 0) {
            //成功
            MemberResponseDTO memberResponseDTO = r.getData("data", new TypeReference<MemberResponseDTO>() {
            });
            log.info("{}用户登录成功,跳转到首页....", memberResponseDTO.getUsername());
            session.setAttribute(SmsConstant.LOGIN_USER, memberResponseDTO);
            return "redirect:http://ingmall.koukoucoding.xn--fiqs8s/";
        } else {
            log.info("{}用户登录失败....", loginVO.getLoginacct());
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.koukoucoding.xn--fiqs8s/login.html";
        }
    }

    /**
     * 登录页的处理逻辑,如果已经登录,去登录页也应该是回到首页
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        MemberResponseDTO member = (MemberResponseDTO) session.getAttribute(SmsConstant.LOGIN_USER);
        if (ObjectUtil.isEmpty(member)) {
            return "login";
        } else {
            return "redirect:http://ingmall.koukoucoding.xn--fiqs8s/";
        }
    }
}
